<?php
namespace common\models\userFund;

use common\models\Common;
use common\models\Status;
use common\models\user\User;
use yii\base\Exception;

/**
 * ContactForm is the model behind the contact form.
 */
class UserMoneyLog extends Common
{
    public static function tableName()
    {
        return '{{%user_money_log}}';
    }

    //获取用户
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }


    /**
     * @param int $userId
     * @param int $prodId
     * @param float|int $num
     * @param int $type
     * @param int $topicId
     * @param string $tag
     * @param string $mark
     * @param bool $record
     * @return bool
     * @throws Exception
     */
    public static function record(
        int $userId = 0, int $prodId = Status::PROP_TYPE_MONEY,
        int $type = Status::MONEY_LOG_TYPE_SEND_RED_PACKET,float $num = 0.00, string $tag = '', string $mark = '',
        int $topicId = 0,
        bool $record = true
    )
    {
        if (empty($num)) {
            return true;
        }

        $propInfo = Status::PROP_TYPE_MAP[$prodId] ?? '';

        if (empty($propInfo)) {
            throw new Exception("参数不能为空");
        }

        if (empty($userId)) {
            throw new Exception("未知用户{$propInfo}");
        }

        if (empty($prodId)) {
            throw new Exception("参数错误{$prodId}");
        }

        if (empty($type) || empty($tag)) {
            throw new Exception("参数不能为空");
        }

        # 获取余额信息
        $where['user_id'] = $userId;
        $where['prop_id'] = $prodId;
        $moneyInfo = UserMoney::getOneByWhere($where);

        $version = $moneyInfo['version'];
        $beforeChange = $moneyInfo['num'] ?? 0;



        if ($num < 0) {
            if (empty($moneyInfo)) {
                switch ($prodId) {
                    case Status::PROP_TYPE_MONEY :
                        $userInfo = User::getOneInfoById($userId,'money');
                        if ($userInfo['money'] < abs($num)) {
                            throw new Exception('用户'.$propInfo.'不足');
                        }
                        $beforeChange = $userInfo['money'] ?? 0;
                        break;

                    case Status::PROP_TYPE_COIN:
                        $userInfo = User::getOneInfoById($userId,'coin');
                        if ($userInfo['coin'] < abs($num)) {
                            throw new Exception('用户'.$propInfo.'不足');
                        }
                        $beforeChange = $userInfo['coin'] ?? 0;
                        break;

                    case Status::PROP_TYPE_SHOP_MONEY:
                        $userInfo = User::getOneInfoById($userId,'shop_money');
                        if ($userInfo['shop_money'] < abs($num)) {
                            throw new Exception('用户'.$propInfo.'不足');
                        }
                        $beforeChange = $userInfo['shop_money'] ?? 0;
                        break;
                }
            }

            if (!empty($moneyInfo) && $moneyInfo['num'] < abs($num)) {
                throw new Exception($propInfo.'不足');
            }
        }


        $db['user_id'] = $userId;
        $db['prop_id'] = $prodId;
        $db['num'] = $num;
        $db['change_type'] = $type;
        $db['change_tag'] = $tag;
        $db['before_change'] = $beforeChange;
        $db['after_change'] = $beforeChange + $num;
        $db['change_time'] = date("Y-m-d H:i:s");
        $db['mark'] = $mark;
        $db['topic_id'] = $topicId;

        if ($record === true) {
            $res = static::insertData($db);
            if (empty($res)) {
                throw new Exception("操作失败");
            }
        }

        switch ($prodId) {
            case Status::PROP_TYPE_MONEY :
                User::updateData(['money' => $db['after_change']], ['id' => $userId]);
                break;

            case Status::PROP_TYPE_COIN:
                User::updateData(['coin' => $db['after_change']], ['id' => $userId]);
                break;

            case Status::PROP_TYPE_SHOP_MONEY:
                User::updateData(['shop_money' => $db['after_change']], ['id' => $userId]);
                break;
        }


        if (!empty($moneyInfo)) {
            $up['num'] = $num;
            $up['version'] = 1;
            $where['version'] = $version;
            $res = UserMoney::updateAllCounters($up, $where);
            if (empty($res)) {
                throw new Exception('系统繁忙');
            }
        } else {
            $up['user_id'] = $userId;
            $up['prop_id'] = $prodId;
            $up['num'] = $db['after_change'];
            $up['create_time'] = date("Y-m-d H:i:s");
            $res = UserMoney::insertData($up);
        }

        if (empty($res)) {
            throw new Exception("信息错误");
        }


        return $res;
    }


}
